package io.awen.modules.sys.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.awen.common.exception.RRException;
import io.awen.common.utils.*;
import io.awen.config.FileConfig;
import io.awen.modules.sys.dao.ToolLocalStorageDao;
import io.awen.modules.sys.entity.FileInfoVo;
import io.awen.modules.sys.entity.ToolLocalStorage;
import io.awen.modules.sys.service.IToolLocalStorageService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

/**
 * @ClassName ToolLocalStorageServiceImpl
 * @Description 本地存储服务层接口实现类
 * @Author gel
 * @Date 2021-01-22
 **/
@Service
@RequiredArgsConstructor
public class ToolLocalStorageServiceImpl extends ServiceImpl<ToolLocalStorageDao, ToolLocalStorage> implements IToolLocalStorageService {
    @Autowired
    private ToolLocalStorageDao toolLocalStorageDao;
    private final FileConfig fileConfig;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ToolLocalStorage> page = this.page(
                new Query<ToolLocalStorage>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ToolLocalStorage create(String name, MultipartFile multipartFile) {
        FileUtils.checkSize(fileConfig.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtils.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtils.getFileType(suffix);
        File file = FileUtils.upload(multipartFile, fileConfig.getPath().getPath() + type +  File.separator);
        if(ObjectUtil.isNull(file)){
            throw new RRException("上传失败");
        }
        try {
            name = StringUtils.isBlank(name) ? FileUtils.getFileNameNoEx(multipartFile.getOriginalFilename()) : name;
            ToolLocalStorage localStorage = new ToolLocalStorage();
            localStorage.setRealName(file.getName());
            localStorage.setName(name);
            localStorage.setSuffix(suffix);
            localStorage.setPath(file.getPath());
            localStorage.setType(type);
            localStorage.setSize(FileUtils.getSize(multipartFile.getSize()));
            localStorage.setCreateTime(new Date());
            localStorage.setCreateUserId(ShiroUtils.getUserId());
            this.save(localStorage);
            String path = file.getPath().replace("\\","/");
            path = path.substring(path.indexOf(fileConfig.getWindows().getRoot()));
            path = fileConfig.getSourceAddress() + "/" + path;
            localStorage.setPath(path);
            return localStorage;
        }catch (Exception e){
            FileUtil.del(file);
            throw new RRException("上传失败");
        }
    }

    @Override
    public void update(ToolLocalStorage toolLocalStorage) {
        toolLocalStorage.setUpdateTime(new Date());
        toolLocalStorage.setUpdateUserId(ShiroUtils.getUserId());
        this.updateById(toolLocalStorage);
    }

    @Override
    public void delete(Set<Long> storageIds) {
        List<ToolLocalStorage> toolLocalStorages = this.list(new QueryWrapper<ToolLocalStorage>().lambda().in(ToolLocalStorage::getStorageId, storageIds));
        toolLocalStorages.forEach(p -> FileUtil.del(p.getPath()));
        baseMapper.deleteBatchIds(storageIds);
    }

    @Override
    public void download(Long storageId) {
        ToolLocalStorage toolLocalStorage = this.getById(storageId);
        FileUtils.downloadFile(RequestHolder.getHttpServletRequest(), RequestHolder.getHttpServletResponse(), new File(toolLocalStorage.getPath()), false);
    }

    @Override
    public List<ToolLocalStorage> info(Set<Long> storageIds) {
        List<ToolLocalStorage> fileList = this.list(new QueryWrapper<ToolLocalStorage>().lambda().in(ToolLocalStorage::getStorageId, storageIds));
        fileList.forEach(p-> {
            String path = p.getPath().replace("\\","/");
            path = path.substring(path.indexOf(fileConfig.getWindows().getRoot()));
            path = fileConfig.getSourceAddress() + "/" + path;
            p.setPath(path);
        });
        return fileList;
    }

    @Override
    public List<ToolLocalStorage> getfileList(Set<Long> ids) {
        FileConfig a = fileConfig;
        System.out.println(a);
        List<ToolLocalStorage> toolLocalStorages = toolLocalStorageDao.getfileList(ids);
        toolLocalStorages.forEach(p-> {
            String path = p.getPath().replace("\\","/");
            path = path.substring(path.indexOf(fileConfig.getWindows().getRoot()));
            path = fileConfig.getSourceAddress() + "/" + path;
            p.setPath(path);
        });
        return toolLocalStorages;
    }

    /**
     * 将文件列表转为[{fileid:1,name:'sf'},{fileid:1,name:'sf'}]
     * @param fileIds 文件ids
     * @return 返回值列表
     */
    @Override
    public String fileList(String fileIds){
        // 如果为空直接返回
        if(StringUtils.isBlank(fileIds)){
            return null;
        }
        // 以逗号隔开转list
        List<String> ids = Arrays.asList(fileIds.split(","));
        List<FileInfoVo> infoVos = new ArrayList<>();
        String result ="";
        // 循环遍历转为list
        for(String id: ids){
            Long id1 =Long.parseLong(id);
            ToolLocalStorage byId = this.getById(id1);
            if(byId != null){
                FileInfoVo infoVo = new FileInfoVo();

                String orgFileName = byId.getName();
                String extName = byId.getSuffix();

                infoVo.setFileId(id);
                // 组合文件名和后缀
                infoVo.setName(orgFileName + (StringUtils.isNotBlank(extName)?"."+extName:""));
                infoVos.add(infoVo);
            }
        }
        // 转为json字符串后返回
        if(infoVos.size() >0){
            result = JSON.toJSONString(infoVos);
        }
        return result;
    }
}
